package com.lizongbo.seotijian.rules;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.Writer;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.SimpleResolver;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;

public class IpWhoisInfoCheckRule extends AbstractCheckRule {
	public final static int DEFAULT_PORT = 43;

	public IpWhoisInfoCheckRule() {
		super();
		this.setMaxPoint(10);
	}

	@Override
	public boolean doCheck(URI uri) {
		if (uri == null) {
			return false;
		}
		String domainName = uri.getHost();
		try {
			String ip = java.net.InetAddress.getByName(domainName)
					.getHostAddress();
			getWhoisInfo(ip);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static String getWhoisInfo(String host) {
		if (host == null || host.length() < 1) {
			return "";
		}
		String whoisServer = "whois.apnic.net";
		String txt = getWhoisInfo(host, whoisServer);
		return txt;
	}

	/**
	 * 获取ip地址的whois信息
	 * 
	 * @param domain
	 * @param whoisServer
	 * @return
	 */
	public static String getWhoisInfo(String domain, String whoisServer) {
		System.err.println("try getWhoisInfo for:" + domain + ",from "
				+ whoisServer);
		return getWhoisInfo(domain, whoisServer, DEFAULT_PORT);
	}

	/**
	 * 从指定的whois服务器获取域名信息
	 * 
	 * @param domain
	 * @param whoisServer
	 * @param whoisServerPort
	 * @return
	 */
	public static String getWhoisInfo(String domain, String whoisServer,
			int whoisServerPort) {
		String rs = "";
		try {
			StringBuilder sb = new StringBuilder(4092);
			Socket theSocket = new Socket(whoisServer, DEFAULT_PORT);
			theSocket.setSoTimeout(1000);
			Writer out = new OutputStreamWriter(theSocket.getOutputStream());
			out.write(domain);
			out.write("\r\n");
			out.flush();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					theSocket.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				sb.append(line).append('\n');
			}
			rs = sb.toString();
		} catch (Exception e) {
			System.err.println("try getWhoisInfo for:" + domain + " from "
					+ whoisServer + ":" + whoisServerPort + ", but err:"
					+ e.getMessage());
			e.printStackTrace();
		}
		return rs;

	}

	public static void main(String[] args) throws IOException, Exception {
		IpWhoisInfoCheckRule whoisInfoCheckRule = new IpWhoisInfoCheckRule();
		String domain = "www.net.cn";// "618119.com";//
		String ip = java.net.InetAddress.getByName(domain).getHostAddress();
		System.out.println(IpWhoisInfoCheckRule.getWhoisInfo(ip));

	}
}
